(function($) {
	$.extend($.fn, {
		fileUpload: function(opts) {
			this.each(function() {

				var default_upload_limit = 4;//默认最多三张
				var upload_limit = 1;//初始化
				var $self = $(this);
				var doms = {
					"fileToUpload": $self.find(".fileToUpload"),
					"thumb": $self.find(".thumb"),
					"progress": $self.find(".upload-progress")
				};
				var files = [];
				var img = new Image();
				var funs = {
					//选择文件，获取文件大小，也可以在这里获取文件格式，限制用户上传非要求格式的文件
					"fileSelected": function() {
						if(opts.upload_limit != undefined) {
							default_upload_limit = opts.upload_limit;
						}
						if(default_upload_limit < upload_limit) {
							mui.alert("提示", "最多允许上传" + default_upload_limit + "张照片");
							return false;
						}
						console.log(upload_limit);
						if(upload_limit==4){
							$(".add").hide();
						}
						var files = (doms.fileToUpload)[0].files;
						var count = files.length;
						
						for(var index = 0; index < count; index++) {
							var file = files[index];
							var fileSize = 0;
							if(file.size < 1024 * 1024){

								fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
							}else{
								fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
							}
							funs.makeBlob(file);
						}
//						funs.uploadFile();
						
						upload_limit++;
					},

					//异步上传文件
					uploadFile: function(files) {
					
						var fd = new FormData(); //创建表单数据对象
						//var files = (doms.fileToUpload)[0].files;
						var count = files.length;
						var previewSpanID;
//						for(var index = 0; index < count; index++) {
//							var file = files[index];
//							var o=opts.file
//							fd.append(opts.file, file); //将文件添加到表单数据中
//
//							previewSpanID = funs.previewImage(file); //上传前预览图片
//						}
//						for(var index = 0; index < count; index++) {
//							var file = files[index];
//							var o=opts.file
//							fd.append(opts.file, funs.dataURItoBlob(file.dataURL),file.name); //将文件添加到表单数据中
//
//							previewSpanID = funs.previewImage(file); //上传前预览图片
//						}
						var o=opts.file
						fd.append(opts.file, funs.dataURItoBlob(files[files.length-1].dataURL),files[files.length-1].name); //将文件添加到表单数据中

						previewSpanID = funs.previewImage(files[files.length-1]); //上传前预览图片	
						var xhr = new XMLHttpRequest();
						xhr.upload.addEventListener("progress", funs.uploadProgress, false); //监听上传进度
						xhr.addEventListener("load", function(e) {
							funs.uploadComplete(e, previewSpanID)
						}, false);
					    xhr.addEventListener("error", opts.uploadFailed, false);
						xhr.open("POST", serverUrl+opts.upload_url);
						xhr.send(fd);
					},
					makeBlob: function(file){
						var reader = new FileReader();
		
		                reader.onloadend = function () {
		                    var img = new Image();
		
		                    img.onload = function () {
		                        // 当图片宽度超过 600px 时, 就压缩成 800px, 高度按比例计算
		                        var w = Math.min(650, img.width);
		                        var h = img.height * (w / img.width);
//		                        var w = img.width;
//		                        var h = img.height;
		                        var canvas = document.createElement('canvas');
		                        var ctx = canvas.getContext('2d');
		
		                        // 设置 canvas 的宽度和高度
		                        canvas.width = w;
		                        canvas.height = h;
		
		                        // 把图片绘制到 canvas 中
		                        ctx.drawImage(img, 0, 0, w, h);
		
		                        // 取出 base64 格式数据
		                        var dataURL = canvas.toDataURL('image/png');
		
		                        files.push({
		                            name: file.name,
		                            dataURL: dataURL
		                        });
		
		                        // 压缩后大小
		                        var after = funs.dataURItoBlob(dataURL);
		                        console.log('压缩后', after.size / 1024);
		                        funs.uploadFile(files);
		                    };
		
		                    // 压缩前大小
		
		                    var before = funs.dataURItoBlob(reader.result);
		                    console.log('压缩前', before.size / 1024);
		
		                    img.src = reader.result;
		                    
		
		                };
		
		                reader.onerror = function () {
		                    console.error('reader error');
		                };
		
		                // 读出base64格式
		                reader.readAsDataURL(file);
					},

					//文件预览
					/**
					 * 
					 * 
					 * @param {Object} file
					 */
					previewImage: function(file) {

						var gallery = doms.thumb;

						//装载每个预览图片容器，创建唯一ID,用作删除
						var li = document.createElement("li");
						var spanID = new Date().getTime();
						li.setAttribute("class", spanID);

						//创建删除元素
						var delete_span=document.createElement("span");
						delete_span.addEventListener("click",function(e){
							funs.removeFile(e, spanID);
							$(".add").show();
						},false);
						
						//图片预览
						var img_div=document.createElement("div");
						var show_shadow = document.createElement("i");
						show_shadow.setAttribute("id","shadow_"+spanID);
						var show_img = document.createElement("img");
						show_img.file = file;
						img_div.appendChild(show_shadow);//进度条
						img_div.appendChild(show_img);
		 
						li.appendChild(delete_span);
						li.appendChild(img_div);
						
						$(doms.thumb).find(".addFile").before(li);

						// 使用FileReader方法显示图片内容
//						var reader = new FileReader();
//						reader.onload = (function(aImg) {
//							return function(e) {
//								aImg.src = e.target.result;
//							};
//						})(show_img);
//						reader.readAsDataURL(file);
						show_img.setAttribute("src",file.dataURL);
						return spanID;
					},
					/**
				     * dataURL to blob, ref to https://gist.github.com/fupslot/5015897
				     * @param dataURI
				     * @returns {Blob}
				     */
					dataURItoBlob : function(dataURI) {
						var byteString = atob(dataURI.split(',')[1]);
				        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
				        var ab = new ArrayBuffer(byteString.length);
				        var ia = new Uint8Array(ab);
				        for (var i = 0; i < byteString.length; i++) {
				            ia[i] = byteString.charCodeAt(i);
				        }
				        return new Blob([ab], {type: mimeString});
					},
					uploadProgress: function(evt) {
						if(evt.lengthComputable) {
							var percentComplete = Math.round(evt.loaded * 100 / evt.total);
							//doms.progress.html(percentComplete.toString() + '%');
							//alert(percentComplete.toString() + '%');
							
						}
					},
					uploadComplete: function(evt, inputID) {
						var responseText = eval("(" + evt.target.responseText + ")");
						var callback = opts.complete;
						if(typeof callback == "function") {
							callback(responseText, inputID);
						}
					},
					removeFile: function(evt, inputID) {
						var fileKey = $("#" + inputID).attr("key") //文件key
						if(utilModule.checkUndefined(fileKey)!=""){
							if(fileKey==null) return;
							utilModule.post({
								url: opts.remove_url,
								data: {"key": fileKey},
								needJson: false,
								async: false,
								success: function(response) {
							}
						  }); 
						}
						upload_limit--;
						$("." + inputID).remove(); 
					},
				};
				doms.fileToUpload.on("change", function() {
					funs.fileSelected()
				}).click(function(){
					if(upload_limit>default_upload_limit){
					   mui.alert("最多允许上传" + default_upload_limit + "张照片","提示");
					   return false;
					}
			
				});
			});
		}
	
	});
})(Zepto);